import { GetUserInfo, UserLoginByRole, UserShareInfo } from '@/api/user';
import useRole from '@/hooks/useRole';
import { DEFAULT_AVATAR } from '@/utils';
import { Button } from '@antmjs/vantui';
import {
  BaseEventOrig,
  ButtonProps,
  Image,
  Text,
  View,
} from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { useRequest } from 'taro-hooks';
import { RoleType } from 'types/user';
import { url2obj } from 'xijs';
import { useAgree } from './components/useAgree';
import { ROLE_HOMEPAGE_MAP, ShowErrorInfoByCode } from './util';

export default function Page() {
  const router = useRouter();
  const scene = decodeURIComponent(router?.params?.scene!);
  const searchParams: any = url2obj(scene);

  const { update: updateRole } = useRole();

  //获取推荐码
  const referCode = router?.params?.refer_code || searchParams?.refer_code;
  referCode && Taro.setStorageSync('refer_code', referCode);

  const { runAsync, loading } = useRequest(UserLoginByRole, {
    manual: true,
  });

  const { agree, renderNode: renderAgreeNode } = useAgree();

  useRequest(GetUserInfo, {
    cacheKey: 'get:user:info',
    onSuccess: async function (data) {
      // 如果是已登录用户
      if (data?.id && data?.status === 1) {
        //更新角色
        data?.role && updateRole(data.role);

        //缓存token
        data?.token && Taro.setStorageSync('token', data.token);

        //根据角色跳转
        Taro.reLaunch({
          url:
            ROLE_HOMEPAGE_MAP[data?.role] || ROLE_HOMEPAGE_MAP[RoleType.用户],
        });
      }
    },
  });

  const { data: user } = useRequest(
    () =>
      UserShareInfo({
        code: referCode,
      }),
    {
      ready: referCode,
      onSuccess: function (res) {
        if (!res.name) {
          Taro.showModal({
            title: '系统提示',
            content: '推荐码已失效',
            showCancel: false,
            success: function () {
              Taro.reLaunch({ url: `/pages/index/index` });
            },
          });
          return;
        }
      },
    }
  );

  async function handleGetPhoneNumber(
    e: BaseEventOrig<ButtonProps.onGetPhoneNumberEventDetail>
  ) {
    if (!agree) {
      e.stopPropagation();
      return Taro.showToast({ title: '请先阅读并同意协议', icon: 'none' });
    }

    const { code, errMsg } = e.detail;
    if (errMsg !== 'getPhoneNumber:ok')
      return Taro.showToast({
        title: '授权失败',
        icon: 'error',
      });
    if (!code) return;
    try {
      const res = await runAsync({
        code,
        role: RoleType.用户,
        reg_code: referCode,
      });

      //判断用户状态
      if (!res)
        await Taro.showToast({ title: '未查询到用用户信息', icon: 'none' });

      //更新角色
      res.role && updateRole(res.role);

      //缓存token
      res?.token && Taro.setStorageSync('token', res.token);

      //通过绑定关系登录之后， 移除
      referCode && Taro.removeStorageSync('refer_code');

      //审核中处理
      if (res.status === 0) {
        return Taro.redirectTo({
          url: res.name ? '/pages/info/success' : `/pages/info/index`,
        });
      }

      // !审核失败
      if (res?.status === 2) {
        return Taro.redirectTo({ url: `/pages/info/fail` });
      }

      //根据角色跳转
      Taro.reLaunch({
        url: ROLE_HOMEPAGE_MAP[res?.role] || ROLE_HOMEPAGE_MAP[RoleType.用户],
      });
    } catch (error: any) {
      const code = error?.code;
      ShowErrorInfoByCode(code);
    }
  }

  return (
    <View
      className='min-h-screen relative overflow-hidden bg-center bg-cover flex flex-col items-center pt-[200px]'
      style={{
        backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/bg4.jpg)`,
      }}
    >
      <Text className=' text-[38px] block text-center text-white'>
        你好，欢迎登录
      </Text>
      <Text className=' text-[48px] block text-center text-white mt-1'>
        臻会帮企业服务平台
      </Text>

      <View
        className='w-[670px] h-[656px] bg-cover mt-[130px] relative'
        style={{
          backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/share-poster-1.png?v=1.0.0)`,
        }}
      >
        <Image
          src={user?.img || DEFAULT_AVATAR}
          mode='aspectFill'
          className='w-[84px] h-[84px] absolute left-[20px] top-[550px] rounded-full'
        />
        {user?.name && (
          <Text className=' text-sm font-bold text-black absolute left-[116px] leading-none top-[554px]'>
            {user?.name}
          </Text>
        )}
      </View>

      <View className=' absolute left-0 right-0 bottom-12 flex flex-col items-center'>
        <Button
          block
          disabled={!agree}
          className='w-[420px] bg-white text-primary mx-auto'
          size='large'
          loading={loading}
          openType='getPhoneNumber'
          onGetPhoneNumber={handleGetPhoneNumber}
        >
          立即授权加入
        </Button>

        {renderAgreeNode()}
      </View>
    </View>
  );
}
